<template>
	<el-card shadow="always" :body-style="{ padding: '20px' }">
		<div class="search-box">
			<el-input
				v-model="queryParams.title"
				placeholder="请输入标题关键词"
				clearable
				style="width: 300px"
				@keyup.enter="handleQuery"
			/>
			<el-button type="primary" @click="handleQuery">搜索</el-button>
			<el-button @click="resetQuery">重置</el-button>
		</div>
		<el-button type="primary" @click="handleAdd">新增</el-button>

		<el-table
			border
			:data="tableData"
			style="width: 100%; margin-top: 20px"
			v-loading="loading"
		>
			<el-table-column prop="id" align="center" width="100" label="id" />
			<el-table-column prop="title" label="标题" show-overflow-tooltip />
			<el-table-column prop="price" width="150" align="right" label="价格(元)">
				<template #default="scope">
					<el-tag type="danger" effect="dark"> {{ scope.row.price }} </el-tag>
				</template>
			</el-table-column>

			<!-- province -->
			<el-table-column width="250" align="center" prop="province" label="省份">
				<template #default="scope">
					<el-tag
						type="info"
						style="margin: 5px"
						v-for="item in scope.row.province.split(',')"
						:key="item"
						>{{ item }}</el-tag
					>
				</template>
			</el-table-column>
			<!-- create_time -->
			<el-table-column label="创建时间" align="center" width="180">
				<template #default="scope">
					{{ formatDateTime(scope.row.createTime) }}
				</template>
			</el-table-column>
			<!-- is_display 是否显示 0-不显示 1-显示 -->
			<el-table-column width="150" align="center" prop="isDisplay" label="是否发布">
				<template #default="scope">
					<el-switch
						v-model="scope.row.isDisplay"
						:active-value="1"
						:inactive-value="0"
						active-color="#13ce66"
						inactive-color="#909399"
						@change="handleStatusChange(scope.row)"
						:disabled="switchLoading"
					/>
				</template>
			</el-table-column>

			<el-table-column label="操作" align="center" fixed="right" width="320">
				<template #default="scope">
					<el-button type="primary" @click="handlePreview(scope.row)">资料录入</el-button>
					<el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<div class="pagination-container">
			<el-pagination
				v-model:current-page="queryParams.pageNum"
				v-model:page-size="queryParams.pageSize"
				:page-sizes="[10, 20, 50, 100]"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			/>
		</div>
	</el-card>

	<!-- 新增/编辑对话框 -->
	<el-dialog
		:title="dialogTitle"
		v-model="dialogVisible"
		width="800px"
		:close-on-click-modal="false"
		:before-close="handleDialogClose"
	>
		<el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px">
			<el-form-item label="标题" prop="title">
				<el-input v-model="formData.title" placeholder="请输入标题" />
			</el-form-item>
			<el-form-item label="价格" prop="price">
				<el-input-number v-model="formData.price" placeholder="请输入价格" />
				<span style="margin-left: 10px; font-style: italic; font-size: 20px"> 元</span>
			</el-form-item>
			<el-form-item label="省份" prop="province">
				<div class="province-checkbox-container">
					<el-checkbox-group v-model="selectedProvinces">
						<el-checkbox v-for="item in provience" :key="item" :label="item">
							{{ item }}
						</el-checkbox>
					</el-checkbox-group>
				</div>
			</el-form-item>
			<el-form-item label="是否发布" prop="isDisplay">
				<el-switch
					v-model="formData.isDisplay"
					:active-value="1"
					:inactive-value="0"
					active-text="发布"
					inactive-text="不发布"
					active-color="#13ce66"
					inactive-color="#909399"
				/>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleDialogClose">取消</el-button>
				<el-button type="primary" @click="submitForm" :loading="submitLoading"
					>确定</el-button
				>
			</span>
		</template>
	</el-dialog>

	<!-- 删除确认对话框 -->
	<el-dialog v-model="deleteDialogVisible" title="确认删除" width="400px">
		<div>确定要删除该记录吗？此操作不可恢复！</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="deleteDialogVisible = false">取消</el-button>
				<el-button type="danger" @click="confirmDelete" :loading="deleteLoading"
					>确定</el-button
				>
			</span>
		</template>
	</el-dialog>

	<!-- 申论预览 -->
	<el-dialog v-model="previewDialogVisible" title="资料录入" fullscreen>
		<slpreview :id="precurrentRow.id" />
	</el-dialog>
</template>

<script setup lang="ts">
import { getSlxx, addSlxx, updateSlxx, deleteSlxx } from '../api/slxx';
import { ref, onMounted, reactive, watch } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { provience } from '../utils/provience';
import Slpreview from './slpreview.vue';
const previewDialogVisible = ref(false);
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);
const switchLoading = ref(false);
const queryParams = ref({
	pageNum: 1,
	pageSize: 10,
	title: ''
});
const precurrentRow = ref<any>({});

// 表单相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const formData = reactive({
	id: '',
	title: '',
	province: '',
	isDisplay: 0,
	price: 0.0
});

// 省份多选
const selectedProvinces = ref<string[]>([]);

// 监听省份选择变化，更新formData.province
watch(
	selectedProvinces,
	newVal => {
		formData.province = newVal.join(',');
	},
	{ deep: true }
);

// 表单验证规则
const formRules = {
	title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
	price: [{ required: true, message: '请输入价格', trigger: 'blur' }]
};

// 删除相关
const deleteDialogVisible = ref(false);
const deleteLoading = ref(false);
const currentRow = ref<any>(null);

const getSlxxData = async () => {
	loading.value = true;
	try {
		const res = await getSlxx(queryParams.value);
		console.log(res.data);
		tableData.value = res.data.records;
		total.value = res.data.total;
	} catch (error) {
		console.error('获取数据失败', error);
	} finally {
		loading.value = false;
	}
};

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
	if (!dateTimeStr) return '';
	return dateTimeStr.replace('T', ' ').split('+')[0];
};

// 查询按钮
const handleQuery = () => {
	queryParams.value.pageNum = 1;
	getSlxxData();
};

// 重置查询
const resetQuery = () => {
	queryParams.value.title = '';
	queryParams.value.pageNum = 1;
	getSlxxData();
};

// 查看详情
const viewDetail = (row: any) => {
	console.log('查看详情', row);
	// 这里可以实现查看详情的逻辑，如跳转到详情页
};

// 每页条数变化
const handleSizeChange = (size: number) => {
	queryParams.value.pageSize = size;
	getSlxxData();
};

// 页码变化
const handleCurrentChange = (page: number) => {
	queryParams.value.pageNum = page;
	getSlxxData();
};

// 新增按钮
const handleAdd = () => {
	resetForm();
	dialogTitle.value = '新增';
	dialogVisible.value = true;
};

// 编辑按钮
const handleEdit = (row: any) => {
	resetForm();
	dialogTitle.value = '编辑';
	// 复制数据到表单
	formData.id = row.id;
	formData.title = row.title;
	formData.price = row.price;
	formData.isDisplay = row.isDisplay;

	// 处理省份字符串转数组
	if (row.province) {
		selectedProvinces.value = row.province.split(',');
	} else {
		selectedProvinces.value = [];
	}

	dialogVisible.value = true;
};

// 删除按钮
const handleDelete = (row: any) => {
	currentRow.value = row;
	deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
	if (!currentRow.value || !currentRow.value.id) return;

	deleteLoading.value = true;
	try {
		await deleteSlxx(currentRow.value.id);
		ElMessage.success('删除成功');
		deleteDialogVisible.value = false;
		getSlxxData(); // 刷新数据
	} catch (error) {
		console.error('删除失败', error);
		ElMessage.error('删除失败');
	} finally {
		deleteLoading.value = false;
	}
};

// 处理表格中状态开关变化
const handleStatusChange = async (row: any) => {
	switchLoading.value = true;
	try {
		await updateSlxx({
			id: row.id,
			isDisplay: row.isDisplay
		});
		ElMessage.success('状态更新成功');
	} catch (error) {
		console.error('状态更新失败', error);
		ElMessage.error('状态更新失败');
		// 恢复原状态
		row.isDisplay = row.isDisplay === 1 ? 0 : 1;
	} finally {
		switchLoading.value = false;
	}
};

// 重置表单
const resetForm = () => {
	formData.id = '';
	formData.title = '';
	formData.province = '';
	formData.isDisplay = 0;
	selectedProvinces.value = [];

	// 重置表单验证
	if (formRef.value) {
		formRef.value.resetFields();
	}
};

// 关闭对话框
const handleDialogClose = () => {
	dialogVisible.value = false;
	resetForm();
};

// 提交表单
const submitForm = async () => {
	if (!formRef.value) return;

	await formRef.value.validate(async valid => {
		if (!valid) return;

		submitLoading.value = true;
		try {
			if (formData.id) {
				// 编辑
				await updateSlxx(formData);
				ElMessage.success('更新成功');
			} else {
				// 新增
				await addSlxx(formData);
				ElMessage.success('添加成功');
			}
			dialogVisible.value = false;
			getSlxxData(); // 刷新数据
		} catch (error) {
			console.error('提交失败', error);
			ElMessage.error('提交失败');
		} finally {
			submitLoading.value = false;
		}
	});
};

// 申论预览
const handlePreview = (row: any) => {
	console.log(row);

	precurrentRow.value = row;
	// setTimeout(() => {
	previewDialogVisible.value = true;
	// }, 200);
};

onMounted(() => {
	getSlxxData();
});
</script>

<style lang="scss" scoped>
.search-box {
	margin-bottom: 20px;
	display: flex;
	gap: 10px;
}

.pagination-container {
	margin-top: 20px;
	display: flex;
	justify-content: flex-end;
}

.dialog-footer {
	display: flex;
	justify-content: flex-end;
	gap: 10px;
}

.province-checkbox-container {
	border: 1px solid #dcdfe6;
	border-radius: 4px;
	padding: 10px;

	.el-checkbox-group {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;

		.el-checkbox {
			margin-right: 0;
			width: calc(25% - 8px);
		}
	}
}
</style>
